﻿using System;
using System.ComponentModel;

namespace NanoMvvm.ComponentModel
{
    public class DelegatePropertyDescriptor : PropertyDescriptor
    {
        private readonly Type ownerType;

        private readonly Type propType;

        internal DelegatePropertyDescriptor(Type ownerType, Type propType, string name, Func<object> getter, Action<object> setter)
            : base(name, new Attribute[] { })
        {
            this.ownerType = ownerType;
            this.propType = propType;

            PropertyGetter = getter;
            PropertySetter = setter;
        }

        public override Type ComponentType
        {
            get
            {
                return ownerType;
            }
        }

        public override bool IsReadOnly
        {
            get
            {
                return PropertySetter == null;
            }
        }

        public override Type PropertyType
        {
            get
            {
                return propType;
            }
        }

        protected Func<object> PropertyGetter { get; private set; }

        protected Action<object> PropertySetter { get; private set; }

        public override bool CanResetValue(object component)
        {
            return false;
        }

        public override object GetValue(object component)
        {
            var val = PropertyGetter != null ? PropertyGetter() : null;
            return val;
        }

        public override void ResetValue(object component)
        {
            // do nothing
        }

        public override void SetValue(object component, object value)
        {
            if (PropertySetter != null)
            {
                PropertySetter(value);
            }
        }

        public override bool ShouldSerializeValue(object component)
        {
            return true;
        }
    }
}